package com.xinxin.socket;

import com.xinxin.socket.handler.DefaultNetMsgHandler;
import com.xinxin.socket.handler.NetMsgHandler;
import com.xinxin.socket.handler.NetMsgHandlerHolder;
import com.xinxin.socket.sample.handler.SampleNetMsgHandler;
import com.xinxin.socket.sample.handler.TopicHandler;
import com.xinxin.socket.server.ProxyServer;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import java.util.List;

@Slf4j
@SpringBootApplication
@ComponentScan({"com.xinxin.socket", "com.xinxin.base"})
public class SocketApplication implements DisposableBean {

    private static ProxyServer proxyServer;

    public static void main(String[] args) {
        SpringApplication.run(SocketApplication.class, args);

        int port = args.length > 0 ? Integer.parseInt(args[0]) : 1969;

        proxyServer = new ProxyServer(new NetMsgHandlerHolder() {

            @Override
            public void addHandler(List<NetMsgHandler> handlers) {
                handlers.add(new TopicHandler());
                handlers.add(new SampleNetMsgHandler());
                handlers.add(new DefaultNetMsgHandler());
            }
        }, port);

        ChannelFuture channelFuture = proxyServer.start();
        channelFuture.addListener(future -> log.info("server started, listener port: {}", port));
    }

    @Override
    public void destroy() throws Exception {
        proxyServer.shutdown();
    }
}
